<template>
  <el-dialog class="public-dialog" title="批量替换订单SKU" width="560" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[10px]">
      <span>选中数据：</span>
      <span class="text-[18px] text-[#3366F1]">{{ rows.length }}</span>
    </p>
    <div>
      <XForm ref="form" :formData="formData" :fieldList="fieldList" :options="formOptions" :rules="rules" />
      <div class="text-[12px] text-[#9DA1AD] leading-[17px] flex items-center">
        <svg-icon icon-class="warning" class="mr-[2px]"></svg-icon>
        替换完SKU后，订单状态将变更为“待确认”，并重新执行系统检测和订单排程！
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button :disabled="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"

import XForm from "@/components/XForm/index.vue"
import { getGoodsSkuList } from "@/api/public.js"
import api from "../../api"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  rows: { type: Array, default: () => [] },
})

const emit = defineEmits(["update:modelValue", "refresh"])

const form = ref()
const formData = ref({})
const loading = ref(false)
const fieldList = ref([
  {
    field: "source",
    type: "select",
    label: "替换前SKU",
    options: {
      data: [],
    },
  },
  {
    field: "target",
    label: "替换后SKU",
  },
])

const handleCheckSku = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入替换后SKU"))
  }

  try {
    const { data } = (await getGoodsSkuList({ sku: [value.trim()] })) || {}
    if (data?.length) {
      callback()
    } else {
      callback(new Error("填写的SKU不存在，请检查！"))
    }
  } catch (e) {
    callback(new Error("填写的SKU不存在，请检查！"))
  }
}

const rules = reactive({
  source: [{ required: true, message: "请选择替换前SKU", trigger: "blur" }],
  target: [{ required: true, validator: handleCheckSku, trigger: "blur" }],
})

watch(
  () => props.rows,
  (val) => {
    if (!val || !val?.length) return
    const _index = fieldList.value.findIndex((n) => n.field === "source")
    let _sku = []
    for (let i = 0; i < val.length; i++) {
      const _productItem = val[i].items
      if (_productItem) {
        for (let j = 0; j < _productItem.length; j++) {
          _sku.push(_productItem[j]?.sku)
        }
      }
    }
    _sku = [...new Set(_sku)]
    fieldList.value[_index].options.data = _sku.map((n) => ({
      label: n,
      value: n,
    }))
  }
)

const handleSave = async () => {
  try {
    loading.value = true
    const orderIds = props.rows?.map((n) => n.id)
    await api.batchReplaceSku({
      ...formData.value,
      orderIds,
    })
    ElMessage.success("替换成功")
    handleClose(true)
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = (refresh) => {
  emit("update:modelValue", false)
  form.value.resetForm()
  if (refresh) emit("refresh")
}

const formOptions = {
  labelPosition: "top",
}
</script>
